using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using SmartLink.Domain.Entity;
using SmartLink.Domain.ExpandEntity.Base;
using SmartLink.Infrastructure;
using SmartLink.IRepository;
using SmartLink.Repository.Base;

namespace SmartLink.Repository
{
    public class SYS_DictionaryRepo : RepositoryBase<SYS_Dictionary>, ISYS_DictionaryRepo
    {
        /// <summary>
        /// 根据字典类型字符串获取字典内容list
        /// </summary>
        /// <param name="category"></param>
        /// <returns></returns>
        public List<SYS_Dictionary> DictionaryList(string category)
        {
            var list = new List<SYS_Dictionary>();
            if (string.IsNullOrEmpty(category))
            {
                return list;
            }

            using (var conn = DapperHelper.GetDefaultConnection())
            {
                var sql = $"select * from SYS_Dictionary where CategoryValue=@Category OR FIND_IN_SET(@Category, Label);";
                list = conn.Query<SYS_Dictionary>(sql, new { Category = category }).ToList();
                return list;
            }
        }

        public dynamic Add(SYS_Dictionary dictionary)
        {
            using (var conn = CreateConn())
            {
                var exists = conn.ExecuteScalar<bool>(@"SELECT EXISTS(SELECT * FROM SYS_Dictionary
                    WHERE CategoryValue=@CategoryValue AND DictionaryItemValue=@DictionaryItemValue)",
                    new { CategoryValue = dictionary.CategoryValue, DictionaryItemValue = dictionary.DictionaryItemValue });
                if (exists) return 0;
                else
                {
                    using (var db = GetIDataBase(conn))
                    {
                        var id = db.Insert(dictionary);
                        return id;
                    }
                }
            }
        }

        public List<AreaExpand> GetAreaList()
        {
            var sql = "select id value,name,parent from sys_area";
            using (var conn = DapperHelper.GetDefaultConnection())
            {
                var result = conn.Query<AreaExpand>(sql).ToList();
                conn.Close();
                return result;
            }
        }
    }
}
